{ Sample program to show how to spool out a PICT file containg the
  image of the Macintosh II main screen
}

{ By Guillermo Ortiz
  Macintosh Developer Technical Support
}

{ This code is provided only as a sample. 
  No claims are made regarding its fitness for any particular purpose
}

{ See IM V for comments and details }

Program ScreenSpool;

USES Memtypes, Quickdraw, OSIntf, ToolIntf, PackIntf;

TYPE BitMapPtr = ^BitMap;

VAR 	pHand2: PicHandle;
  		globalRef: INTEGER;
		
Procedure PutPICTData(dataPtr: Ptr; byteCount: Integer);

VAR longCount:LONGINT;

BEGIN
	longCount:= byteCount;
	IF FSWrite( globalRef, longCount, dataPtr) <> noErr THEN Debugger;
	IF pHand2 <> NIL THEN
	  pHand2^^.picSize:=pHand2^^.picSize + longCount;
END;

PROCEDURE SpitItOut;
VAR
  err: OSErr;
  i, vrefnum: INTEGER;
  longCount,
  longZero: LONGINT;
  reply: SFReply;	        { reply record }
  myProcs: CQDProcs;
  volName: Str255;
  currGDHand: GDHandle;
  where: Point;
  oldPort: GrafPtr;
  myPort:CGrafPort;
  myPortPtr: CGrafPtr;
  myDev: GDHandle;
   
BEGIN
		 GetPort(oldPort);
		 myPortPtr:= @myPort; 	{ initialize }
		 OpenCPort(myPortPtr);	{ set my port }
		 
		 where.h:= 20;
		 where.v:=20;
		 SFPutFile(where,'Save picture as: ','untitled',NIL,reply);IF NOT(reply.good) THEN Debugger;
		 Err:= GetVol(@volName,reply.vrefnum);IF err<>0 THEN Debugger;
		 err:= Create(reply.fName,reply.vrefnum,'.GAO','PICT');IF err<>0 THEN Debugger;
		 err := FSOpen(reply.fName,reply.vrefnum, globalRef); IF err<>0 THEN Debugger;

		 pHand2 := NIL; { The bottle neck proc checks this to see if it needs to save size }
		
		 SetPort(GrafPtr(myPortPtr));
		 
		 SetStdCProcs(myProcs);
		 GrafPtr(myPortPtr)^.grafProcs:=@myProcs;
		 myProcs.putPicProc:=@PutPictData;
		 
		 
		 myDev:= GetMainDevice;
		 
		 longZero := 0;
		 longCount := 4;
		 FOR i := 1 TO (512 + SizeOf(Picture)) DIV 4 DO
		   err := FSWrite (globalRef, longCount, @longZero);

	  	  ClipRect(myDev^^.gdPMap^^.bounds); {Comment this out and nothing will save to disk! }

		 pHand2 := OpenPicture (myDev^^.gdPMap^^.bounds);
		 
{ This copybits call saves the contents of the whole screen into the PICT }
		 CopyBits(BitMapPtr(myDev^^.gdPMap^)^, 
		          BitMapPtr(myDev^^.gdPMap^)^,
		          myDev^^.gdPMap^^.bounds,
		  		  myDev^^.gdPMap^^.bounds,
				  0, NIL);
	     ClosePicture;
	   
		 IF SetFPos (globalRef, fsFromStart, 512) <> noErr THEN Debugger;
		 longCount := SizeOf(Picture); {GetHandleSize(Handle(pHand2));}
	     IF FSWrite (globalRef,longCount , Ptr(pHand2^)) <> noErr THEN Debugger;

	     IF FSClose (globalRef) <> noErr THEN Debugger;

 		 GrafPtr(myPortPtr)^.grafProcs:=NIL;
		 
	     KillPicture (pHand2);
		 SetPort(oldPort);
END; {SpitItOut}

BEGIN
		InitGraf(@thePort);
		InitFonts;
		FlushEvents(everyEvent, 0);
		InitWindows;
		InitMenus;
		TEInit;
		InitDialogs(NIL);
		InitCursor;
		
		SpitItOut;
END.